/***
 *  Platypus: Page Layout and Typesetting Software (free at platypus.pz.org)
 *
 *  Platypus is (c) Copyright 2006-11 Pacific Data Works LLC. All Rights Reserved.
 *  Licensed under Apache License 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html)
 */

package org.pz.platypus.utilities;

import java.io.File;
import java.util.*;

/**
 * Gets the home directory for Platypus as set in the user environment.
 * Checks command-line, then PLATYPUS_HOME in environment, then current directory.
 * Adds a file separator to end of path and validates that it's a directory.
 * @author alb
 */
public class PlatypusHomeDirectory
{
    private String home;

    public PlatypusHomeDirectory( String[] args )
    {
        home = checkCommandLine( args );
        if( home == null ) {
            home = checkEnvironment();
            if( home == null )
                home = checkCurrentDir();
        }

        if( home != null )
            home = validateHome( home );

        if( home == null ) {
            System.out.println( "Cannot find Platypus Home. See documentation. Exiting..." );
            throw new MissingResourceException( null, null, null );
        }
    }

    protected String checkCurrentDir()
    {
        return( System.getProperty( "user.dir" ));
    }

    protected String checkCommandLine( final String[] args )
    {
        if( args!= null && Arrays.asList( args ).contains( "-home" )) {
            int home = Arrays.asList( args ).indexOf( "-home" );
            if( args.length >= home )
                return( args[home+1] );
        }
        return( null );
    }

    protected String checkEnvironment()
    {
        final String PlatypusEnvString = "PLATYPUS_HOME";
        return( System.getenv( PlatypusEnvString ));
    }

    // add a file separator to path, then check that there's a config directory below it.
    protected String validateHome( final String  homeString )
    {
        if( homeString != null ) {
            String homeDirectory = FileSeparator.append( homeString );

            File f = new File( homeDirectory + "config" );
            if( f.exists() && f.isDirectory() )
                return( homeDirectory );
        }
        return( null );
    }

    public String get()
    {
        return( home );
    }
}
